﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Forums.SqlServer.Repositories.Readers
{
	using System.Data.SqlClient;
	using Falcon.Core.Domain;
	using Falcon.Core.SqlServer.Repositories.Readers;
	using Falcon.Forums.Domain;
	using Falcon.Forums.Domain.Enums;

	public class ForumReader : IReader<Forum>
	{
		/// <summary>
		/// Populates the specified reader.
		/// </summary>
		/// <param name="reader">The reader.</param>
		/// <param name="entity">The entity.</param>
		public void Populate(SqlDataReader reader, Forum entity)
		{
			entity.Id = reader.GetInt32(0);

			if (!reader.IsDBNull(1))
			{
				entity.ParentId = reader.GetInt32(1);
			}

			entity.Title = reader.GetString(2);
			entity.Slug = reader.GetString(3);
			entity.Body = (reader.IsDBNull(4)) ? null : reader.GetString(4);
			entity.BodyParsed = (reader.IsDBNull(5)) ? null : reader.GetString(5);
			entity.Password = (reader.IsDBNull(6)) ? null : reader.GetString(6);

			entity.Total = new ForumTotal
			{
				Topics = reader.GetInt32(7), 
				Posts = reader.GetInt32(8)
			};

			entity.Order = reader.GetInt32(9);
			entity.Html = reader.GetBoolean(10);
			entity.BBCode = reader.GetBoolean(11);
			entity.Smilies = reader.GetBoolean(12);
			entity.Scope = (ForumScope)reader.GetInt32(13);
			entity.Status = (ForumStatus)reader.GetInt32(14);
			entity.ViewAge = (ForumViewAge)reader.GetInt32(15);
			entity.Created = reader.GetDateTime(16);
			entity.Updated = reader.GetDateTime(17);

			if (reader.IsDBNull(18))
			{
				return;
			}

			entity.LastPost = new ForumPost
          	{
				Id = reader.GetInt32(18),
				TopicId = reader.GetInt32(19),
          		Title = reader.GetString(20),
          		Slug = reader.GetString(21),
          		Created = reader.GetDateTime(22),
          		Updated = reader.GetDateTime(23),
          		User = new User
				{
					Id = reader.GetInt32(24),
					Name = reader.GetString(25),
					Slug = reader.GetString(26),
					Reputation = reader.GetInt32(27),
					Profile = new UserProfile { Title = reader.GetString(28) }
				}
          	};

			if (!reader.IsDBNull(29))
			{
				entity.LastPost.User.Profile.Avatar = new UserAvatar
				{
					FileName = reader.GetString(29),
					FileDiskName = reader.GetString(30),
					FilePath = reader.GetString(31),
					FileType = reader.GetString(32)
				};
			}
		}
	}
}